import router from './router'
import store from './store'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  const Token = store.getters.token
  if (Token) {
    if (to.path === '/login') {
      next('/') // 路由后置守卫对于next('')，里面有路径的情况，不会执行，所以要手动关闭进度条
      NProgress.done()
    } else {
      if (!store.getters.userId) { // 获取用户名和 ID
        store.dispatch('user/getUserInfo')
      }

      next() // 放行
    }
  } else { // 没有token
    if (whiteList.includes(to.path)) { // 在白名单
      next()
    } else {
      next('/login') // 中转到登录页
      NProgress.done()
    }
  }
})

// 后置导航守卫
router.afterEach(() => {
  // 清除进度条
  NProgress.done()
})
